package cn.yj.wx.pay.service;

import cn.yj.common.interfaces.ISign;
import cn.yj.params.check.annotation.Require;
import cn.yj.tools.exception.ServiceException;
import cn.yj.wx.pay.config.WxPayConfig;
import cn.yj.wx.pay.enrity.NoticeBody;
import cn.yj.wx.pay.utils.WxPayUtils;
import com.google.gson.Gson;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import javax.annotation.Resource;
import java.security.GeneralSecurityException;
import java.util.Map;

/**
 * @author 永健
 * @since 2022-02-19 14:22
 */
public class WechatPaySign implements ISign, ApplicationContextAware {

    @Resource
    private WxPayConfig payConfig;


    private static ApplicationContext app;

    public static WechatPaySign getInstance() {
        if (app == null) {
            throw new ServiceException("未启用支付宝支付");
        }
        return app.getBean(WechatPaySign.class);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        app = applicationContext;
    }

    @Override
    public boolean decryptSign(@Require Map<String, String> params) {
        Gson gson = new Gson();
        try {
            WxPayUtils.checkPayNotice(gson.fromJson(gson.toJson(params), NoticeBody.class),payConfig.getApiV3Key());
        } catch (GeneralSecurityException e) {
            e.printStackTrace();
            throw new ServiceException(e.getMessage());
        }
        return true;
    }
}
